package top.lingkang.springboothibernate.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.Serializable;
import java.util.Properties;

/**
 * 采用雪花算法生成主键
 * 2021年7月11日22:11:55
 */
public class PrimaryGenerator implements Configurable, IdentifierGenerator {
    //参数1为终端ID
    //参数2为数据中心ID
    Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    private String pre = "";

    @Override
    public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
        String prefix = params.getProperty("prefix");
        if (prefix != null)
            this.pre = prefix;
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        //雪花算法生成ID
        return pre + snowflake.nextIdStr();
    }
}
